<template>
  <el-dialog draggable :title="title" :model-value="visible" @closed="close" width="332">
    <el-table :data="categoryList" border fit v-loading="showLoading">
        <el-table-column
            :prop="item.dataKey"
            :label="item.title"
            :width="item.width"
            resizable show-overflow-tooltip
            :formatter="handleFormatter"
            :key="item.dataKey"
            v-for="item in tableHeader"/>
        <el-table-column label="操作" width="60">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  </el-dialog>
</template>

<script setup>
import {getPersonBillCategoryRef, usePersonDeleteBillCategory} from "@/composition/billSys/usePersonBill.js";
import zhCN from "element-plus/es/locale/lang/zh-cn";
import {useCompanyBillCategoryDelete, useCompanyBillCategoryRefById} from "@/composition/billSys/useCompanyBill.js";

const props = defineProps(['visible', 'title', 'isCompany', 'companyId']);
const emit = defineEmits(['cancel', 'update:visible']);
const {
  visible,
  title,
  isCompany,
  companyId
} = toRefs(props);

const initCategoryListRef = () => {
  const categoryListTemp = ref([]);
  // 个人
  if (!isCompany.value) {
    let personCategoryObj = getPersonBillCategoryRef();
    watch(() => personCategoryObj.value, (newValue) => {
      categoryListTemp.value = [...Object.values(newValue)];
    }, {immediate: true, deep: true});
    return categoryListTemp;
  }
  // 公司
  let companyCategoryObj = useCompanyBillCategoryRefById(companyId.value);
  watch(() => companyCategoryObj.value, (newValue) => {
    categoryListTemp.value = [...Object.values(newValue)];
  }, {immediate: true, deep: true});
  return categoryListTemp;
};
const initTableHeader = () => {
  return [
    {
      dataKey: 'name',
      title: '名称',
      width: 120
    },
    {
      dataKey: 'isOut',
      title: '支出/收入',
      width: 120
    }
  ];
};
const categoryList = initCategoryListRef();
const tableHeader = initTableHeader();
const showLoading = ref(false);

const handleFormatter = (row, col, value, index) => {
  if (col.property === 'isOut') {
    return value ? '支出' : '收入';
  }
  return value;
};

const handleDelete = async (index, rowData) => {
  showLoading.value = true;
  try {
    if (!isCompany.value) {
      // 个人
      await usePersonDeleteBillCategory(rowData.id);
    } else {
      // 公司
      await useCompanyBillCategoryDelete(companyId.value, rowData.id);
    }
  } catch (e) {
    console.log(e);
  }
  showLoading.value = false;
};


const close = () => {
  emit('update:visible', false);
  emit('cancel');
};


</script>

<style scoped lang="scss">

</style>
